package gxprod.androidai.support;



/**
 * Converts numbers into fractions multiplied by mathmatical constants. Constants are optional.
 * @author josh
 */
public final class FriendlyNumber {

	private static final double[] constants = {
		Math.PI,
		Math.E
	};

	private static final String[] constantStrings = {
		"π", "e", 
	};



	public static String convertToFriendlyNumber(double input, boolean consts) {
		String header = "";
		double temp;

		// constants	

		if(consts) {
			for(int i = 0; i < constants.length; i++) {
				temp = input / constants[i] * 1000;

				if(Math.round(temp) == temp) {
					header += constantStrings[i];
					input /= constants[i];
					i--;
				}
			}
		}

		// roots




		// fractions

		double afterDecimal = input - (input - Math.round(input));

		if(afterDecimal != 0) {
			int after, denominator = 1;
			while(afterDecimal != Math.round(afterDecimal))  {
				afterDecimal *= 10;
				denominator *= 10;
			}
			after = (int)afterDecimal;
			int gcd = gcd(after, denominator);
			if(gcd > 1) {
				after /= gcd;
				denominator /= gcd;	
				return header + " " + Math.round(input) + " " + after + " / " + denominator;
			}
		}

		if(input == 1.0)
			return header;

		return header + " " + input;
	}


	public static int gcd(int a, int b) {
		if (b==0) 
			return a;

		return gcd(b,a%b);
	}
}
